package apa.wings.gwtCRUD.server.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import apa.wings.gwtCRUD.server.domain.Person;

public class PersonDAOHibernate extends HibernateDaoSupport implements PersonViejo {

	private static final Log logger = LogFactory.getLog(PersonDAOHibernate.class);
	
	public void save(Person person) {

		Session session = null;
		Transaction tx = null;

		try {
			session = getSession();
			tx = session.beginTransaction();
			session.saveOrUpdate(person);
			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			logger.error("Error saving person", e);

		} finally {
			releaseSession(session);
		}
	}

	public void delete(Person person) {

		Session session = null;
		Transaction tx = null;

		try {
			session = getSession();
			tx = session.beginTransaction();
			session.delete(person);
			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			logger.error("Error deleting Person", e);

		} finally {
			releaseSession(session);
		}
	}

	public Person find(int id) {
		Session session = null;
		Transaction tx = null;

		try {
			session = getSession();
			tx = session.beginTransaction();
			Person person = (Person) session.get(Person.class, new Integer(id));
			tx.commit();
			return person;

		} catch (RuntimeException re) {
			tx.rollback();
			logger.error("Error al recuperar el escritor", re);
			throw re;

		} finally {
			releaseSession(session);
		}
	}

	public List<Person> getPersonList() {

		Session session = null;
		Transaction tx = null;

		try {
			session = getSession();
			tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(Person.class);
			@SuppressWarnings("unchecked")
			List<Person> persons = criteria.list();
			tx.commit();
			return persons;
		}

		catch (RuntimeException re) {
			logger.error("Error retriving Persons list", re);
			throw re;

		} finally {
			releaseSession(session);
		}
	}

}
